<?php

namespace App;

use Illuminate\Database\Eloquent\Builder;

/**
 * Class Post
 * @package App
 * 文章模型
 */
class Post extends Model
{

    protected $table = 'posts';

    protected $primaryKey = 'id';

    //定义es索引里面的type
    public function searchableAs()
    {
        return "post_index";
    }

    //定义es type中的field
    public function toSearchableArray()
    {
        return [
            'title' => $this->title,
            'content' => $this->content
        ];
    }

    //文章查找用户一对一反向:首页用到
    public function user()
    {
        return $this->belongsTo('\App\User');
    }

    //文章查找评论一对多
    public function comments()
    {
        return $this->hasMany('\App\Comment')->orderBy('created_at', 'desc');
    }

    //某人是否点赞这篇文章
    public function zan($user_id)
    {
        return $this->hasOne('\App\Zan')->where('user_id', $user_id);
    }

    //文章赞数
    public function zans()
    {
        return $this->hasMany('\App\Zan');
    }

    //属于某一个作者的文章
    public function scopeAuthorBy(Builder $query, $user_id)
    {
        return $query->where('user_id', $user_id);
    }

    //文章查找文章表和专题表的关系表一对多
    public function postTopics()
    {
        return $this->hasMany(\App\PostTopic::class, 'post_id', 'id');
    }

    //不属于某一个专题的文章
    public function scopeTopicNotBy(Builder $query, $topic_id)
    {
        return $query->doesntHave('postTopics', 'and', function ($q) use ($topic_id) {
            $q->where('topic_id', $topic_id);
        });
    }

    //全局scope
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope("avaiable", function(Builder $builder){
            $builder->whereIn('status',[0,1]);
        });
    }

}
